import Vue from 'vue'
import { getWechatFriendList, getBlack ,addBlack } from '@/api/admin/custom'

// initial state
const state = {
  currentNav: 'newFriend', // 工具大全当前的页面 默认是微信好友请求
  newFriendsList: [], // 新的朋友圈列表
  weChatIds: {}, // 工具大全每个页面所选的微信id
  searchResult: {}, // 号码、微信号的查询结果
  phoneState: {} // 手机状态
}

// getters
const getters = {
  currentWeChatId: (state) => {
    const cn = state.currentNav
    return state.weChatIds[cn] ? state.weChatIds[cn] : ''
  }, // 当前页面选择的微信
  phoneState: (state) => state.phoneState,
  newFriendsList: (state) => state.newFriendsList
}

// actions
const actions = {}

// mutations
const mutations = {
  // 设置tools当前的页面
  SET_CURRENT_NAV: (state, nav) => {
    state.currentNav = nav
  },
  // 设置每个页面 选择的wxid
  SET_CURRENT_WECHAT_IDS: (state, msg) => {
    Vue.set(state.weChatIds, msg.nav, msg.weChatId)
  },
  // 设置号码查微信的结果
  SET_SEARCH_RESULT: (state, searchData) => {
    state.searchResult = searchData
  },
  // 重置手机状态
  RESET_PHONE_STATE: (state) => {
    state.phoneState = {}
  },
  // 设置手机状态
  SET_PHONE_STATE: (state, data) => {
    Vue.set(state.phoneState, data.WeChatId, data)
  },
  // 设置新的好友列表
  SET_NEW_FRIENDS_LIST: async (state, newFriendsData) => {
    const { Requests, WeChatId } = newFriendsData;
  
    // 1. 预处理请求数据
    Requests.forEach(x => {
      x.WeChatId = WeChatId;
    });
    
    // 2. 合并并排序原始列表
    let arr = state.newFriendsList.concat(Requests).sort((a, b) => {
      return b.ReqTime - a.ReqTime;
    });
    
    // 3. 同步处理：为每个请求创建数据获取任务
    const tasks = arr.map(item => {
      return Promise.all([
        getWechatFriendList(item.FriendId).then(res => res.data),
        getBlack(item.FriendId).then(res => res.data)
      ]).then(([friends, black]) => {
        return { ...item, friends, black };
      });
    });
    
    // 4. 等待所有任务完成后更新状态
    Promise.all(tasks).then(updatedItems => {
      state.newFriendsList = updatedItems;
    }).catch(error => {
      console.error('获取好友列表或黑名单失败:', error);
      // 可添加错误处理逻辑，如设置错误状态
    });
  },
  // 重置新的好友
  RESET_NEW_FRIENDS_LIST: (state) => {
    state.newFriendsList = []
  },
  // 更新申请状态
  UPDATE_ACCEPTE_STATE: (state, row) => {
    state.newFriendsList.splice(row.ri, row.rd)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
